//
//  FlickrController.m
//  Words2
//
//  Created by Mathieu on 27/09/06.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import <WebKit/WebKit.h>
#import "FlickrController.h"
#import "OFDemoAPIKey.h"
#import "WordsAppDelegate.h"
#import "ImageMO.h"
#import "ImagesController.h"
@implementation FlickrController


#pragma mark Words Accessors (API)
- (IBAction)getImages:(id)sender{
	[progressIndicator startAnimation:nil];
	[[self apicaller] cancel];
	NSString *tags = [[[wordArrayController selectedObjects] objectAtIndex:0] valueForKey:@"word"];
	[[self apicaller] setSelector:@selector(handleImages:error:data:)];
	[[self apicaller] callMethod:@"flickr.photos.search" arguments:[NSArray arrayWithObjects:@"tags", tags, nil]];
}

- (void)setImagesForWord:(WordMO *)word{
	OFFlickrInvocation *caller = [[OFFlickrInvocation alloc] initWithDelegate:self context:[self flickrContext]];
	NSString *tags = [word valueForKey:@"word"];
	[caller setSelector:@selector(setImagesForWord:error:data:)];
	[caller setUserInfo:word];
	[caller callMethod:@"flickr.photos.search" arguments:[NSArray arrayWithObjects:@"tags", tags, nil]];

}

-(void)setImagesForWord:(OFFlickrInvocation*)caller error:(int)errcode data:(id)data{
	WordMO *word = [caller userInfo];
	
	id dataInnards = [data flickrDictionaryFromDocument];
	[dataInnards objectForKey:@"photo"];
	NSArray *photosArray = [[dataInnards objectForKey:@"photos"] objectForKey:@"photo"];
	NSEnumerator *e = [photosArray objectEnumerator];
	//loop through the first few
	int number = 0;
	NSDictionary *thePhoto;
	//get the first five images
	while(thePhoto = [e nextObject] && (number < 5)){
		thePhoto = [photosArray objectAtIndex:number]; 
		NSLog([thePhoto description]);
		NSString *photoURLString  = [[self flickrContext] photoURLFromID:[thePhoto objectForKey:@"@id"]  serverID:[thePhoto objectForKey:@"@server"]  secret:[thePhoto objectForKey:@"@secret"]  size:@"m" type:nil];
		NSLog(@"Looking up photo with URL: %@", photoURLString); 
		NSURL * photoURL = [NSURL URLWithString:photoURLString];
		NSImage *imageFile = [[NSImage alloc] initWithContentsOfURL:photoURL];
		
		//create a new Image Entity
		NSManagedObjectContext *moc = [[NSApp delegate] managedObjectContext];
		ImageMO *newImageMO = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:moc];
		//set it's attributes
		[newImageMO setImage:imageFile];
		[newImageMO setValue:photoURLString forKey:@"webURL"]; //where it came from
		[newImageMO setValue:[thePhoto objectForKey:@"@title"] forKey:@"name"];
		
		[newImageMO setValue:word forKey:@"word"];
		
		number++;
	}
	[caller autorelease];
	[progressIndicator stopAnimation:nil];
	
}

//this is where we pick up the cargo.

-(void)handleImages:(OFFlickrInvocation*)caller error:(int)errcode data:(id)data{
	
	if(errcode < 0){
		NSLog(@"Error: %d Not Flickr's fault!", errcode);
		return;
	}
	if(errcode > 0){
		NSLog(@"Error: %d Flickr's fault! %@", errcode, data);
		return;
	}
//	if(errcode == OFFlickrInvocationCancelled){
//		return;
//	}
	else{
		id dataInnards = [data flickrDictionaryFromDocument];
		[dataInnards objectForKey:@"photo"];
		NSDictionary *photos = [dataInnards objectForKey:@"photos"]; 
		id photosArray = [[dataInnards objectForKey:@"photos"] objectForKey:@"photo"];
		NSEnumerator *e = [photosArray objectEnumerator];
		//loop through the first few
		int number = 0;
		int resultsCount = [[photos objectForKey:@"@total"] intValue];
		NSDictionary *thePhoto;
		
		if(resultsCount == 1){
			//we only found one photo so we have to extract it differently
			NSString *photoURLString  = [[self flickrContext] photoURLFromID:[photosArray objectForKey:@"@id"]  serverID:[photosArray objectForKey:@"@server"]  secret:[photosArray objectForKey:@"@secret"]  size:@"m" type:nil];
			NSLog(@"Looking up photo with URL: %@", photoURLString); 
			NSURL * photoURL = [NSURL URLWithString:photoURLString];
			NSImage *imageFile = [[NSImage alloc] initWithContentsOfURL:photoURL];
			
			//create a new Image Entity
			NSManagedObjectContext *moc = [[NSApp delegate] managedObjectContext];
			ImageMO *newImageMO = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:moc];
			//set it's attributes
			[newImageMO setImage:imageFile];
			[newImageMO setValue:photoURLString forKey:@"webURL"]; //where it came from
			[newImageMO setValue:[photosArray objectForKey:@"@title"] forKey:@"name"];
			
			[imageArrayController addObject:newImageMO];
		}
		else{
								//get the first five images
			while(thePhoto = [e nextObject] && (number < 5)){
				thePhoto = [photosArray objectAtIndex:number]; 
				NSLog([thePhoto description]);
				NSString *photoURLString  = [[self flickrContext] photoURLFromID:[thePhoto objectForKey:@"@id"]  serverID:[thePhoto objectForKey:@"@server"]  secret:[thePhoto objectForKey:@"@secret"]  size:@"m" type:nil];
				NSLog(@"Looking up photo with URL: %@", photoURLString); 
				NSURL * photoURL = [NSURL URLWithString:photoURLString];
				NSImage *imageFile = [[NSImage alloc] initWithContentsOfURL:photoURL];
				
				//create a new Image Entity
				NSManagedObjectContext *moc = [[NSApp delegate] managedObjectContext];
				ImageMO *newImageMO = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:moc];
				//set it's attributes
				[newImageMO setImage:imageFile];
				[newImageMO setValue:photoURLString forKey:@"webURL"]; //where it came from
				[newImageMO setValue:[thePhoto objectForKey:@"@title"] forKey:@"name"];
				
				[imageArrayController addObject:newImageMO];
				
				number++;
			}
		}
	}
	
	[progressIndicator stopAnimation:nil];

// What we can get from an image
//	<NSCFDictionary 0x32cd30>{
//	@title = Applej00z;
//	@server = 82;
//	@isfamily = 0;
//	@id = 255427308;
//	@ispublic = 1;
//	@isfriend = 0;
//	@secret = ac0599312b;
//	@owner = 68626984@N00;

	
}

@end
